<template>
  <div class="caregiver-accident-container">
    <div class="header">
      <h2>事故记录</h2>
      <p>管理您负责的长者事故记录</p>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchParams.elderName"
            placeholder="搜索长者姓名"
            clearable
            @clear="handleSearch"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-select
            v-model="searchParams.accidentType"
            placeholder="选择事故类型"
            clearable
            @change="handleSearch"
          >
            <el-option label="跌倒" value="跌倒" />
            <el-option label="烫伤" value="烫伤" />
            <el-option label="迷路" value="迷路" />
            <el-option label="走失" value="走失" />
            <el-option label="突发疾病" value="突发疾病" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select
            v-model="searchParams.severity"
            placeholder="选择严重程度"
            clearable
            @change="handleSearch"
          >
            <el-option label="轻微" value="轻微" />
            <el-option label="一般" value="一般" />
            <el-option label="严重" value="严重" />
            <el-option label="危急" value="危急" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 操作按钮 -->
    <div class="action-section">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增事故记录
      </el-button>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="elderName" label="长者姓名" width="120" />
        <el-table-column prop="accidentType" label="事故类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getAccidentTypeTag(row.accidentType)">
              {{ row.accidentType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="accidentTime" label="发生时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.accidentTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="severity" label="严重程度" width="100">
          <template #default="{ row }">
            <el-tag :type="getSeverityTag(row.severity)">
              {{ row.severity }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="location" label="发生地点" width="150" />
        <el-table-column prop="description" label="事故描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="handlingMeasures" label="处理措施" min-width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="记录时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              size="small"
              type="primary"
              link
              @click="handleView(row)"
            >
              查看详情
            </el-button>
            <el-button
              size="small"
              type="warning"
              link
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              link
              @click="handleDelete(row.accidentId)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="长者" prop="elderId">
          <el-select
            v-model="formData.elderId"
            placeholder="选择长者"
            style="width: 100%"
            :disabled="isEdit"
          >
            <el-option
              v-for="elder in elderList"
              :key="elder.elderId"
              :label="elder.name"
              :value="elder.elderId"
            />
          </el-select>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="事故类型" prop="accidentType">
              <el-select
                v-model="formData.accidentType"
                placeholder="选择事故类型"
                style="width: 100%"
              >
                <el-option label="跌倒" value="跌倒" />
                <el-option label="烫伤" value="烫伤" />
                <el-option label="迷路" value="迷路" />
                <el-option label="走失" value="走失" />
                <el-option label="突发疾病" value="突发疾病" />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="严重程度" prop="severity">
              <el-select
                v-model="formData.severity"
                placeholder="选择严重程度"
                style="width: 100%"
              >
                <el-option label="轻微" value="轻微" />
                <el-option label="一般" value="一般" />
                <el-option label="严重" value="严重" />
                <el-option label="危急" value="危急" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="发生时间" prop="accidentTime">
          <el-date-picker
            v-model="formData.accidentTime"
            type="datetime"
            placeholder="选择发生时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="发生地点" prop="location">
          <el-input
            v-model="formData.location"
            placeholder="请输入发生地点"
          />
        </el-form-item>
        <el-form-item label="事故描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请详细描述事故经过"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="处理措施" prop="handlingMeasures">
          <el-input
            v-model="formData.handlingMeasures"
            type="textarea"
            :rows="3"
            placeholder="请描述采取的处理措施"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="目击信息" prop="witnessInfo">
          <el-input
            v-model="formData.witnessInfo"
            type="textarea"
            :rows="2"
            placeholder="请输入目击者信息"
          />
        </el-form-item>
        <el-form-item label="后续跟进" prop="followUp">
          <el-input
            v-model="formData.followUp"
            type="textarea"
            :rows="2"
            placeholder="请输入后续跟进计划"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="formData.status"
            placeholder="选择状态"
            style="width: 100%"
          >
            <el-option label="待处理" value="pending" />
            <el-option label="处理中" value="processing" />
            <el-option label="已处理" value="resolved" />
            <el-option label="已关闭" value="closed" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 详情查看对话框 -->
    <el-dialog
      title="事故详情"
      v-model="detailVisible"
      width="700px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="长者姓名">{{ detailData.elderName }}</el-descriptions-item>
        <el-descriptions-item label="事故类型">{{ detailData.accidentType }}</el-descriptions-item>
        <el-descriptions-item label="发生时间">{{ formatDateTime(detailData.accidentTime) }}</el-descriptions-item>
        <el-descriptions-item label="严重程度">
          <el-tag :type="getSeverityTag(detailData.severity)">
            {{ detailData.severity }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="发生地点" :span="2">{{ detailData.location }}</el-descriptions-item>
        <el-descriptions-item label="事故描述" :span="2">{{ detailData.description }}</el-descriptions-item>
        <el-descriptions-item label="处理措施" :span="2">{{ detailData.handlingMeasures }}</el-descriptions-item>
        <el-descriptions-item label="目击信息" :span="2">{{ detailData.witnessInfo || '无' }}</el-descriptions-item>
        <el-descriptions-item label="后续跟进" :span="2">{{ detailData.followUp || '无' }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusTag(detailData.status)">
            {{ getStatusText(detailData.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="记录时间">{{ formatDateTime(detailData.createTime) }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import { getMyElders } from '@/api/elder.js'
import { getAccidentsByCaregiver, addAccidentRecord, updateAccidentRecord, deleteAccidentRecord } from '@/api/accident.js'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const detailVisible = ref(false)
const submitting = ref(false)
const formRef = ref()
const elderList = ref([])

// 搜索参数
const searchParams = reactive({
  elderName: '',
  accidentType: '',
  severity: ''
})

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref([])

// 表单数据
const formData = reactive({
  accidentId: null,
  elderId: '',
  accidentType: '',
  accidentTime: '',
  severity: '一般',
  location: '',
  description: '',
  handlingMeasures: '',
  witnessInfo: '',
  followUp: '',
  status: 'pending'
})

// 详情数据
const detailData = reactive({
  elderName: '',
  accidentType: '',
  accidentTime: '',
  severity: '',
  location: '',
  description: '',
  handlingMeasures: '',
  witnessInfo: '',
  followUp: '',
  status: '',
  createTime: ''
})

// 表单验证规则
const formRules = {
  elderId: [{ required: true, message: '请选择长者', trigger: 'change' }],
  accidentType: [{ required: true, message: '请选择事故类型', trigger: 'change' }],
  accidentTime: [{ required: true, message: '请选择发生时间', trigger: 'change' }],
  severity: [{ required: true, message: '请选择严重程度', trigger: 'change' }],
  location: [{ required: true, message: '请输入发生地点', trigger: 'blur' }],
  description: [{ required: true, message: '请输入事故描述', trigger: 'blur' }],
  handlingMeasures: [{ required: true, message: '请输入处理措施', trigger: 'blur' }]
}

// 计算属性
const dialogTitle = computed(() => formData.accidentId ? '编辑事故记录' : '新增事故记录')
const isEdit = computed(() => !!formData.accidentId)

// 方法
const getAccidentTypeTag = (type) => {
  const tagMap = {
    '跌倒': 'warning',
    '烫伤': 'danger', 
    '迷路': 'info',
    '走失': 'danger',
    '突发疾病': 'danger',
    '其他': 'primary'
  }
  return tagMap[type] || 'info'
}

const getSeverityTag = (severity) => {
  const tagMap = {
    '轻微': 'success',
    '一般': 'info',
    '严重': 'warning',
    '危急': 'danger'
  }
  return tagMap[severity] || 'info'
}

const getStatusTag = (status) => {
  const tagMap = {
    'pending': 'warning',
    'processing': 'primary',
    'resolved': 'success',
    'closed': 'info'
  }
  return tagMap[status] || 'info'
}

const getStatusText = (status) => {
  const textMap = {
    'pending': '待处理',
    'processing': '处理中',
    'resolved': '已处理',
    'closed': '已关闭'
  }
  return textMap[status] || status
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  // 如果是字符串格式的时间，直接返回
  if (typeof dateTime === 'string') {
    // 检查是否是有效的日期字符串
    if (!isNaN(Date.parse(dateTime))) {
      const date = new Date(dateTime)
      return `${date.getFullYear()}/${(date.getMonth() + 1).toString().padStart(2, '0')}/${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`
    }
    // 如果是已经格式化的字符串，直接返回
    return dateTime;
  }
  // 如果是日期对象，格式化为指定格式
  return `${dateTime.getFullYear()}/${(dateTime.getMonth() + 1).toString().padStart(2, '0')}/${dateTime.getDate().toString().padStart(2, '0')} ${dateTime.getHours().toString().padStart(2, '0')}:${dateTime.getMinutes().toString().padStart(2, '0')}:${dateTime.getSeconds().toString().padStart(2, '0')}`
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      elderName: searchParams.elderName,
      accidentType: searchParams.accidentType,
      severity: searchParams.severity
    }

    const response = await getAccidentsByCaregiver(await getCurrentCaregiverId(), params)
    tableData.value = response.data.records || []
    pagination.total = response.data.total || 0
  } catch (error) {
    console.error('加载事故记录失败:', error)
    ElMessage.error('加载事故记录失败')
  } finally {
    loading.value = false
  }
}

const getCurrentCaregiverId = () => {
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
  return userInfo.caregiverId || ''
}


// 加载护工负责的长者列表
const loadElderList = async () => {
  try {
    const response = await getMyElders()
    elderList.value = response.data || []
  } catch (error) {
    console.error('加载长者列表失败:', error)
  }
}


// 搜索处理
const handleSearch = () => {
  pagination.currentPage = 1
  loadData()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadData()
}

// 新增记录
const handleAdd = () => {
  Object.keys(formData).forEach(key => {
    if (key !== 'accidentId') {
      formData[key] = ''
    }
  })
  formData.accidentId = null
  formData.severity = '一般'
  formData.status = 'pending'
  dialogVisible.value = true
}

// 编辑记录
const handleEdit = (row) => {
  Object.assign(formData, {
    accidentId: row.accidentId,
    elderId: row.elderId,
    accidentType: row.accidentType,
    accidentTime: row.accidentTime ? new Date(row.accidentTime) : '',
    severity: row.severity,
    location: row.location,
    description: row.description,
    handlingMeasures: row.handlingMeasures,
    witnessInfo: row.witnessInfo,
    followUp: row.followUp,
    status: row.status
  })
  dialogVisible.value = true
}

// 查看详情
const handleView = (row) => {
  Object.assign(detailData, {
    elderName: row.elderName,
    accidentType: row.accidentType,
    accidentTime: row.accidentTime,
    severity: row.severity,
    location: row.location,
    description: row.description,
    handlingMeasures: row.handlingMeasures,
    witnessInfo: row.witnessInfo,
    followUp: row.followUp,
    status: row.status,
    createTime: row.createTime
  })
  detailVisible.value = true
}

// 删除记录
const handleDelete = async (accidentId) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条事故记录吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteAccidentRecord(accidentId)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除事故记录失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitting.value = true
    
    const submitData = { ...formData }
    
    // 处理时间字段
    if (submitData.accidentTime) {
      if (typeof submitData.accidentTime === 'string') {
        // 如果是字符串，直接使用
        submitData.accidentTime = submitData.accidentTime
      } else if (submitData.accidentTime instanceof Date) {
        // 如果是Date对象，转换为格式化字符串
        submitData.accidentTime = formatDateTime(submitData.accidentTime)
      }
    }
    
    // 移除 accidentId 属性，避免传递给后端
    const { accidentId, ...dataToSend } = submitData;
    
    if (formData.accidentId) {
      await updateAccidentRecord(formData.accidentId, dataToSend)
      ElMessage.success('更新成功')
    } else {
      await addAccidentRecord(submitData)
      ElMessage.success('新增成功')
    }
    
    dialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('提交表单失败:', error)
    if (error.errors) {
      ElMessage.error('请检查表单填写是否正确')
    } else {
      ElMessage.error('操作失败')
    }
  } finally {
    submitting.value = false
  }
}

// 初始化数据
onMounted(() => {
  loadData()
  loadElderList()
})

// 添加日期格式化方法
Date.prototype.format = function(fmt) {
  const o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "H+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S": this.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (let k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    }
  }
  return fmt;
}

</script>
